package it.unipd.dei.bd.icineasti.database;

import it.unipd.dei.bd.icineasti.resource.Utente;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.sql.Timestamp;

/**
 * Ritorna l'utente associato ad una certa email e password.
 * 
 * @author Bardelle Renzo
 * @version 1.00
 */

public class GetAssociatedUtenteDatabase {

	private static final String STATEMENT1 = "SELECT * FROM utente WHERE email = ? and password = ?";
	private static final String STATEMENT2 = "UPDATE utente  SET ultimoaccesso = ? WHERE email = ? and password = ?";
	
	private final Connection con;

	private final String insertedEmail;
	private final String insertedMd5Pw;

	private Utente u;
	
	public GetAssociatedUtenteDatabase(Connection con, String insertedEmail, String insertedMd5Pw) {
		this.con = con;
		this.insertedEmail = insertedEmail;
		this.insertedMd5Pw = insertedMd5Pw;
	}

	public Utente getUtente() throws SQLException {

		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;
		
		PreparedStatement pstmt2 = null;
		

		try {
			
			pstmt1 = con.prepareStatement(STATEMENT1);
			pstmt2 = con.prepareStatement(STATEMENT2);
			
			pstmt1.setString(1, insertedEmail);
			pstmt1.setString(2, insertedMd5Pw);
			
			pstmt2.setTimestamp(1, new Timestamp(System.currentTimeMillis())); 
			pstmt2.setString(2, insertedEmail);
			pstmt2.setString(3, insertedMd5Pw);
			
			rs1 = pstmt1.executeQuery();

			while (rs1.next())
				u = new Utente(
							rs1.getInt("idutente"),
							rs1.getString("email"),
							rs1.getString("password"),
							rs1.getString("cognome"),
							rs1.getString("nome"),
							rs1.getString("codfiscale"),
							rs1.getString("cartacredito"),
							null,
							rs1.getBoolean("attivo"),
							rs1.getBoolean("newsletter"),
							rs1.getBoolean("amministrativo"),
							rs1.getBoolean("verificato"));
			if(u != null)
			{
			  pstmt2.executeUpdate();
			}
			
		} finally {
			if (rs1 != null) {
				rs1.close();
			}

			if (pstmt1 != null) {
				pstmt1.close();
			}
			
			if (pstmt2 != null) {
				pstmt2.close();
			}

			con.close();
		}

		return u;
	}
}